<template>
  <el-row>
    <el-col :span="24" v-loading="httpLoading">
      <ProductionSelectModal @setProduction="setProduction" :visible.sync="selectVisible"></ProductionSelectModal>
      <el-form :model="model" label-position="left" ref="elForm" label-width="120px">
        <!--新增 (无id: 头部表单：-->
        <Portlet :title="isEdit ? '编辑' : '新增' + '商品'">
          <template slot="tools">
            <el-button type="primary" @click.prevent="selectVisible = true">选择商品</el-button>
          </template>
          <el-row :gutter="15">
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="厂家名称：">
                <span>{{ production.manufacturersName }}</span>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="编号：">
                <span>{{ production.productNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="类别：">
                <span>{{ production.bigClass }} / {{ production.middleClass }}</span>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="规格：">
                <span>{{ production.standard }}</span>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="名称：">
                <span>{{ production.productName }}</span>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="售价："
                :rules="[
                  {required: true, message: '售价必须', trigger: 'blur'},
                  {validator: isFormatNumber, message: '售价必须是数字', trigger: 'blur'},
                  {validator: range, min: 0, message: '售价必须大于0', trigger: 'blur'},
                ]"
                prop="price">
                <el-input v-model="model.price">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="虚拟库存："
                :rules="[
                  {required: true, message: '虚拟库存必须', trigger: 'blur'},
                  {validator: isInteger, message: '虚拟库存必须是整数', trigger: 'blur'},
                  {validator: range, min: 0, message: '虚拟库存必须大于0', trigger: 'blur'},
                ]"
                prop="inventory">
                <el-input v-model="model.inventory">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="虚拟库存单位："
                :rules="[
                  {required: true, message: '库存单位必须', trigger: 'change'}
                ]"
                prop="unit">
                <el-input v-model="model.unit">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item label="上架状态：" prop="productState">
                <el-switch
                  v-model="model.productState"
                  active-text="立即上架"
                  inactive-text="不上架"
                  :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item
                label="商品图片："
                :rules="[
                  {required: true, message: '商品图片必须', trigger: 'change', type: 'array'}
                ]"
                prop="pictureArr">
                <upload-image v-model="model.pictureArr" :max="4"></upload-image>
                <span class="font-red">最多四张, 正方形的图片</span>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="货号："
                prop="itemNo">
                <el-input maxlength="50" v-model="model.itemNo">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="型号："
                prop="model">
                <el-input maxlength="50" v-model="model.model">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="材质："
                prop="texture">
                <el-input maxlength="50" v-model="model.texture">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="功能："
                prop="purpose">
                <el-input maxlength="50" v-model="model.purpose">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="风格："
                prop="style">
                <el-input maxlength="50" v-model="model.style">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :md="12" :lg="8" :xl="6">
              <el-form-item
                label="空间："
                prop="space">
                <el-input maxlength="50" v-model="model.space">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item
                label="关联门店："
                prop="productShopList">
                <el-checkbox-group v-model="model.productShopList">
                  <el-checkbox :key="item.value" v-for="item in productShopListOptions" :label="item.value">
                    {{ item.text }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>

            <el-col :md="24" :lg="24">
              <el-form-item label="商品介绍" prop="productAbstract">
                <Tinymce :height=400 ref="editor" v-model="model.productAbstract"/>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <!--按钮-->
        <el-row>
          <Portlet>
            <el-row>
              <el-col :span="24" class="text-center">
                <el-button type="default" @click.prevent="toIndex" :loading="createLoading">取消</el-button>
                <el-button v-if="!isEdit" type="primary" :loading="createLoading"
                           @click.prevent="httpCreatePost(false)">提交并继续创建
                </el-button>
                <el-button type="primary" :loading="createLoading" @click.prevent="httpCreatePost()">
                  {{ isEdit ? '保存' : '提交' }}
                </el-button>
              </el-col>
            </el-row>
          </Portlet>
        </el-row>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import {copy, dotData, alert} from '@/utils'
import {isFormatNumber, isInteger, range} from '@/utils/validate'
import Tinymce from '@/components/Tinymce'
import ProductionSelectModal from '@/views/oms/shop/ProductionSelectModal'
export default {
  components: {
    Tinymce,
    ProductionSelectModal
  },
  props: {
    addRoleNum: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      model: {
        productId: '',
        price: '',
        inventory: '',
        unit: '',
        productState: 1,
        itemNo: '',
        model: '',
        texture: '',
        purpose: '',
        style: '',
        space: '',
        productAbstract: '',
        productShopList: [],
        pictureArr: []
      },
      productShopListOptions: [],
      loading: false,
      selectVisible: false,
      production: {},
      createLoading: false,
      httpLoading: false
    }
  },
  computed: {
    // 是否是新增编辑页
    isEdit() {
      return !!this.id
    }
  },
  created() {
    if (this.isEdit) {
      this.getDetail()
    }
    this.httpGetProductShopList()
  },
  methods: {
    isFormatNumber,
    isInteger,
    range,
    // 新增 提交
    httpCreatePost(redirect = true) {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let data = copy(this.model, true)
        const productId = dotData(this.production, 'productId')
        if (productId) {
          data.productId = productId
        } else {
          alert('请选择商品信息')
          return
        }
        if (this.id) {
          data.id = this.id
        }
        // 处理图片
        data.picture = data.pictureArr.join(',')
        delete data.pictureArr
        this.createLoading = true
        const url = this.isEdit ? '/ms-warehouse-store/product/update-product' : '/ms-warehouse-store/product/add-product'
        this.$ajax.post(url, data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm((this.isEdit ? '编辑' : '新增') + '成功', '提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              this.resetFields()
              if (redirect) {
                this.toIndex()
              }
            })
          }
          this.createLoading = false
        }).catch(_ => {
          this.createLoading = false
        })
      })
    },
    // 修改时 请求roleId名+权限id 并 回填 下半截：
    getDetail() {
      this.httpLoading = true
      this.$ajax.get('/ms-warehouse-store/product/get-product-info', {id: this.id}).then(response => {
        const success = response.success
        if (success) {
          // 产品设置
          this.production.productId = dotData(response, 'data.productId')
          this.production.manufacturersName = dotData(response, 'data.manufacturersName')
          this.production.productNo = dotData(response, 'data.productNo')
          this.production.bigClass = dotData(response, 'data.bigClass')
          this.production.middleClass = dotData(response, 'data.middleClass')
          this.production.standard = dotData(response, 'data.standard')
          this.production.productName = dotData(response, 'data.productName')
          // model 设置
          this.model.price = dotData(response, 'data.price')
          this.model.inventory = dotData(response, 'data.inventory')
          this.model.unit = dotData(response, 'data.unit')
          this.model.productState = dotData(response, 'data.productState')
          const picture = dotData(response, 'data.picture')
          if (picture && typeof picture === 'string') {
            this.model.pictureArr = picture.split(',')
          }
          this.model.itemNo = dotData(response, 'data.itemNo')
          this.model.model = dotData(response, 'data.model')
          this.model.texture = dotData(response, 'data.texture')
          this.model.purpose = dotData(response, 'data.purpose')
          this.model.style = dotData(response, 'data.style')
          this.model.space = dotData(response, 'data.space')
          this.model.productAbstract = dotData(response, 'data.productAbstract')
          const mallShopInfos = dotData(response, 'data.mallShopInfos')
          if (Array.isArray(mallShopInfos)) {
            this.model.productShopList = mallShopInfos.map(v => v.id)
          }
        }
      }).finally(_ => {
        this.httpLoading = false
      })
    },
    // 获取关联门店
    httpGetProductShopList() {
      this.$ajax.get('/ms-warehouse-store/shop/get-mallShopInfo-list', {shopState: 1}).then(response => {
        if (response.success) {
          if (Array.isArray(response.data)) {
            this.productShopListOptions = response.data.map(v => {
              return {
                value: v.id,
                text: v.shopName
              }
            })
          }
        }
      })
    },
    // 设置产品
    setProduction(production) {
      if (production) {
        this.production = production
      }
    },
    // 重置表单
    resetFields() {
      const elForm = this.$refs.elForm
      this.production = {}
      if (elForm) {
        elForm.resetFields()
      }
    },
    // 跳转列表
    toIndex() {
      this.$router.push({path: '/redirect/ss-oms/shop/goods'})
    }
  }
}
</script>
